// index.js
// 获取应用实例
const app = getApp()
const md5 = require("../../utils/md5");

Page({
  data: {
    words: [],
    loading: false,
    distMap: null,
    appid: "20210319000733456",
    curTran: "",
    curText: "",
    curIndex: 0,
    playStatus: false,
    player: null,
    speed: 800,
    mode: 1,
    words_backup: null
  },
  onLoad() {
    wx.setInnerAudioOption({
      obeyMuteSwitch: false
    })
    wx.showLoading({
      title: '正在加载',
    })
    wx.request({
      url: 'https://j-an-x.gitee.io/frontend-words/words.json',
      success: (res) => {
        let list = res.data.sort();
        this.setData({
          words: list,
        }, () => {
          wx.hideLoading()
        })
      }
    })
  },
  onHide() {
    if (this.data.player && this.data.playStatus) {
      this.data.player.pause();
      this.data.playStatus = false;
    }
  },
  startPlay() {
    if (!this.data.words.length || !this.data.playStatus) return;
    this.query(this.data.words[this.data.curIndex], this.data.curIndex);
  },
  query(s, index) {
    let salt = new Date().getTime();
    let md5_str = md5.hex_md5(`${this.data.appid}${s}${salt}VioPuzm6nUHgXYGn2bk_`);
    if (!this.data.distMap) {
      this.data.distMap = new Map();
    }
    if (this.data.distMap.has(s)) {
      this.setData({
        curText: s,
        curTran: this.data.distMap.get(s).dit
      }, () => {
        if (this.data.distMap.get(s).tts) {
          this.paly(this.data.distMap.get(s).tts);
        } else {
          this.setData({
            curIndex: ++this.data.curIndex
          }, () => {
            setTimeout(this.startPlay, this.data.speed)
          })
        }
      })
    } else {
      wx.request({
        url: `https://fanyi-api.baidu.com/api/trans/vip/translate?q=${s}&tts=0&dict=1&from=en&to=zh&appid=${this.data.appid}&salt=${salt}&sign=${md5_str}`,
        success: (res) => {
          this.data.distMap.set(s, {
            dit: res.data.trans_result[0].dst,
            tts: res.data.trans_result[0].src_tts
          });
          console.log(s, this.data.distMap)
          this.setData({
            curText: s,
            curTran: res.data.trans_result[0].dst
          }, () => {
            if (this.data.distMap.get(s).tts) {
              this.paly(this.data.distMap.get(s).tts);
            } else {
              this.setData({
                curIndex: ++this.data.curIndex
              }, () => {
                setTimeout(this.startPlay, this.data.speed)
              })
            }
          })

        }
      })
    }

  },
  paly(url) {
    let innerAudioContext = null;
    if (this.data.player) {
      innerAudioContext = this.data.player;
    } else {
      // this.setData({
      //   player: wx.createInnerAudioContext()
      // }, () => {
      //   innerAudioContext = this.data.player;
      // })
      innerAudioContext = this.data.player = wx.createInnerAudioContext();
      innerAudioContext.onEnded(() => {
        this.setData({
          curIndex: ++this.data.curIndex
        }, () => {
          setTimeout(this.startPlay, this.data.speed)
        })
      })
    }
    innerAudioContext.autoplay = true;
    innerAudioContext.src = url;


  },
  handletap() {
    this.setData({
      playStatus: !this.data.playStatus
    }, () => {
      if (!this.data.playStatus) {
        this.data.player.pause();
      } else {
        if (this.data.player) {
          this.data.player.play();
        } else {
          this.startPlay();

        }
      }
    })
  },
  replay() {
    if (this.data.player) {
      this.data.player.offEnded();
      this.data.player.destroy();
      this.setData({
        player: null,
        playStatus: false,
        curIndex: 0,
        curText: "",
        curTran: ""
      })
    }
  },
  speedChange(event) {
    this.setData({
      speed: event.detail.value
    })
  },
  switchMode() {
    if (this.data.mode === 1) {
      let arr = this.shuffle(this.data.words);
      this.setData({
        mode: 2,
        words: arr
      }, () => {
        this.replay();
      })
    } else {
      this.data.words.sort();
      this.setData({
        mode: 1
      }, () => {
        this.replay();
      })
    }
  },
  shuffle(array) {
    let m = array.length,
      t, i;
    while (m) {
      i = Math.floor(Math.random() * m--);
      t = array[m];
      array[m] = array[i];
      array[i] = t;
    }
    return array;
  }
})